package com.qiandw.mailSendService.service;


import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.context.Context;
import org.thymeleaf.spring5.SpringTemplateEngine;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;


@Service
public class MailSenderService {

    private final Logger logger = LoggerFactory.getLogger(MailSenderService.class);
    private final JavaMailSender javaMailSender;
    private final SpringTemplateEngine templateEngine;
    private final MailContextEditService mailContextEditService;

    @Setter
    @Getter
    private String received = "coxx";

    @Value("${spring.mail.username}")
    private String sender;


    public JavaMailSender getJavaMailSender() {
        return javaMailSender;
    }

    @Autowired
    public MailSenderService(JavaMailSender javaMailSender, SpringTemplateEngine templateEngine, MailContextEditService mailContextEditService) {
        this.javaMailSender = javaMailSender;
        this.templateEngine = templateEngine;
        this.mailContextEditService = mailContextEditService;
    }

    @Async
    public void sendSimpleMail(String subject, String senderContext){
        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(sender);
        simpleMailMessage.setTo(received);
        simpleMailMessage.setSubject(subject);
        simpleMailMessage.setText(senderContext);
        Date nowDate = Calendar.getInstance().getTime();
        simpleMailMessage.setSentDate(nowDate);
        javaMailSender.send(simpleMailMessage);
    }

    void sendHtmlStyleMail(String subject, String htmlStyleContext){
        MimeMessage message = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(message);
        Date nowDate = Calendar.getInstance().getTime();
        try {
            helper.setFrom(sender);
            helper.setTo(received);
            helper.setSubject(subject);
            helper.setSentDate(nowDate);
            helper.setText(htmlStyleContext, true);
        } catch (MessagingException e) {
            e.printStackTrace();
            logger.error("发送html风格类型mail出错",e);
        }
        javaMailSender.send(message);
    }

    public void sendInlineMail(String subject, String htmlStyleContext, Resource resource){
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(sender);
            helper.setTo(received);
            helper.setSubject(subject);
            //第二个参数指定发送的是HTML格式,同时cid:是固定的写法
            helper.setText("<html><body>带静态资源的邮件内容 图片:<img src='cid:picture' /></body></html>", true);
            helper.addInline("picture", resource);
        } catch(MessagingException e) {
            e.printStackTrace();
            logger.error("发送html Inline 风格类型mail出错",e);
        }
        javaMailSender.send(message);
    }

    public void sendAttachmentMail(String subject, String htmlStyleContext, Resource resource){
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(sender);
            helper.setTo(received);
            helper.setSubject(subject);
            //第二个参数指定发送的是HTML格式,同时cid:是固定的写法
            helper.addAttachment("picture_logo.png", resource);
        } catch(MessagingException e) {
            e.printStackTrace();
            logger.error("发送html addAttachment 风格类型mail出错",e);
        }
        javaMailSender.send(message);
    }

    @Async
    public void sendTemplateMail(String subject, Map<String, Object> model, String templateUrl){
        MimeMessage message = javaMailSender.createMimeMessage();
        try {
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            helper.setFrom(sender);
            helper.setTo(received);
            helper.setSubject(subject);
            //设置context
            Context context = new Context();
            context.setVariables(model);
            String templates = templateEngine.process(templateUrl, context);
            System.out.println(templates);
            //使用生成pdf
            String outputPath = "src/main/resources/pdf/" + System.currentTimeMillis() + ".pdf";
            mailContextEditService.generate(templates, outputPath); //生成pdf
            mailContextEditService.sign(outputPath, outputPath); //签章
            helper.setText(templates, true);
        } catch(MessagingException e) {
            e.printStackTrace();
            logger.error("发送html TemplateMail 风格类型mail出错",e);
        }
        javaMailSender.send(message);
    }

    private String simpleComponentContext(String subject, String context){
        StringBuffer buffer = new StringBuffer();
        buffer.append("<h1>" + subject + "</h1>")
                .append("<p style='color:#F00'>")
                .append(context).append("</p>");
        return buffer.toString();
    }

    @Async
    public void sendSimpleHtmlMail(String subject, String context){
        String htmledContext = simpleComponentContext(subject, context);
        sendHtmlStyleMail(subject, htmledContext);
    }
}
